/**
 * 
 */
package com.ph.shopping.facade.supplier.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.constant.CommonConstants;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.RoleEnum;
import com.ph.shopping.common.core.customenum.SmsCodeType;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.rsa.MD5;
import com.ph.shopping.facade.mapper.SupplierChargeRecordMapper;
import com.ph.shopping.facade.mapper.SupplierDrawcashRecordMapper;
import com.ph.shopping.facade.mapper.SupplierImageMapper;
import com.ph.shopping.facade.mapper.SupplierMapper;
import com.ph.shopping.facade.member.service.ISmsCodeSendService;
import com.ph.shopping.facade.permission.dto.UserRoleDto;
import com.ph.shopping.facade.permission.entity.User;
import com.ph.shopping.facade.permission.service.IUserService;
import com.ph.shopping.facade.supplier.entity.Supplier;
import com.ph.shopping.facade.supplier.entity.SupplierChargeRecord;
import com.ph.shopping.facade.supplier.entity.SupplierDrawcashRecord;
import com.ph.shopping.facade.supplier.entity.SupplierImage;
import com.ph.shopping.facade.supplier.service.ISupplierService;
import com.ph.shopping.facade.supplier.vo.SupplierBalanceRecordVo;
import com.ph.shopping.facade.supplier.vo.SupplierVo;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @项目：phshopping-service-Supplier
 *
 * @描述：供应商接口实现
 *
 * @作者： liuy
 *
 * @创建时间：2017年3月15日
 *
 * @Copyright @2017 by liuy
 */
@Component
@Service(version="1.0.0")
public class SupplierServiceImpl extends BaseService implements ISupplierService{
	
    @Autowired
    SupplierMapper supplierMapper;
    
	@Autowired
	private SupplierImageMapper supplierImageMapper;

	//供应商充值记录
	@Autowired
	private SupplierChargeRecordMapper supplierChargeRecordMapper;
	
	//供应商提现记录
	@Autowired
	private SupplierDrawcashRecordMapper supplierDrawcashRecordMapper;
	
    //用户接口
	@Reference(version="1.0.0")
	private IUserService iUserService;
	
	//发送短信接口
	 @Reference(version="1.0.0",timeout=30000)
	 private ISmsCodeSendService smsCodeSendService;
    
	/**
	 * 生成随机密码
	 * 
	 * @return
	 */
	public static String getSmsCode() {
		return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
	}
	
    @Override
	public Result getSupplierVoPageList(PageBean page,SupplierVo supplierVo) {
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<SupplierVo> list=(Page<SupplierVo>)supplierMapper.getSupplierVoListByPage(supplierVo);
		PageInfo<SupplierVo> pageInfo=new PageInfo<SupplierVo>(list);
		return getResult(ResultEnum.SUCCESS,pageInfo.getList(),pageInfo.getTotal());
    }

    @Override
    public List<SupplierVo> getSupplierVoList(Supplier supplier) {
    	List<SupplierVo> list = supplierMapper.getSupplierVoList(supplier);
		return list;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Result addSupplier(Supplier supplier, List<SupplierImage> imageList) throws BizException {
    	
    	Long deleteUserId = 0l;//用于供应商新增失败时，回滚用户新增的操作
    	Result result = getResult(ResultEnum.SUCCESS); 
    	//新增里面捕捉了异常，因为调用了用户接口。其他方法，不捕捉异常，在Controller中捕捉
    	try {
    		logger.info("供应商新增");
    		if("".equals(supplier.getPositionId())){
    			supplier.setPositionId(null);
    		}

			//1.新增一个用户,返回id
	        UserRoleDto dto = new UserRoleDto();
	        dto.setTelphone(supplier.getPersonTel());
	        dto.setRoleCode(RoleEnum.SUPPLIER.getCode());//设置为供应商类型
	        Result userResult = iUserService.addUser(dto);//新增用户,调用用户接口
	        
	        //调用用户接口后，判断1.result是否为空;2.返回的Code是否为“用户已注册”;3.判断是否返回成功Code
	        if (null != result&& !ResultEnum.REGISTERED.getCode().equals(userResult.getCode())
	        		&& ResultEnum.SUCCESS.getCode().equals(userResult.getCode())){

		        Long userId = (Long) userResult.getData();//返回的Id
		        deleteUserId = userId;//用于供应商新增失败时，回滚用户新增的操作
		        
				// 2.新增供应商
		        supplier.setId(userId);//--这里为supplier设置主键为user返回的id,供应商id和userId一样，业务要求
	    		this.supplierMapper.insert(supplier);
	    		
				// 3.将供应商id赋值给图片的ProductId，保存图片
				for (SupplierImage image : imageList) {
					image.setSupplierId(userId);//--这里的id和userId一样
					image.setCreateTime(new Date());
					image.setUpdateTime(new Date());
				}
				if(imageList.size()!=0){
					//保存图片
					this.supplierImageMapper.insertList(imageList);
				}
	        } else{
	        	result.setCode(userResult.getCode());
	        	result.setMessage(userResult.getMessage());
	        }
	        
		} catch (Exception e) {
			//如果新增供应商失败了，删除用户
			 User userDelete = new User();
			 userDelete.setId(deleteUserId);
			iUserService.deleteUser(userDelete);
			
			e.printStackTrace();
			logger.error("供应商新增异常:" + e.getMessage());
			result = getResult(ResultEnum.ADD_SUPPLIER_EXCEPTION);
			throw new BizException("供应商新增异常:70012");
		}
		return result;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Result updateSupplier(Supplier supplier, List<SupplierImage> imageList) throws BizException {
    	Result result = getResult(ResultEnum.SUCCESS); 
    	
		logger.debug("供应商修改");
		logger.debug("supplier: " + supplier);
		logger.debug("imageList: " + imageList);
		
		//设置删除已有的图片条件
		Example example = new Example(SupplierImage.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("supplierId", supplier.getId());
		
		//修改供应商
    	supplier.setUpdateTime(new Date());

    	//如果省、市、区有为空字符串的，改为null
//		if("".equals(supplier.getProvinceId())){
//			supplier.setProvinceId(null);
//		}
//		if("".equals(supplier.getCityId())){
//			supplier.setCityId(null);
//		}
//		if("".equals(supplier.getCountyId())){
//			supplier.setCountyId(null);
//		}
		if("".equals(supplier.getPositionId())){
			supplier.setPositionId(null);
		}
    	
    	supplierMapper.updateByPrimaryKeySelective(supplier);
    	
    	//删除已有的图片
    	supplierImageMapper.deleteByExample(example);
    	
    	if(imageList.size()!=0){
    		//新增当前图片
        	supplierImageMapper.insertList(imageList);
    	}

		return result; 	
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Result batchDeleteSupplier(List<Long> list)  throws BizException {
		for(Long id:list){
    		SupplierVo supplierVo = new SupplierVo();
    		supplierVo.setId(id);
    		//先物理删除图片信息
    		supplierMapper.deleteSupplierImage(supplierVo);
		}
		//逻辑删除供应商信息
    	supplierMapper.batchDeleteSupplier(list);
        return getResult(ResultEnum.SUCCESS);
    }
    
    @Override
    @Transactional(rollbackFor=Exception.class)
    public Result congealSupplier(Supplier supplier)  throws BizException {
    	Result result = getResult(ResultEnum.SUCCESS); 
    	try{
	    	//1.冻结或者解冻账号
	    	User user = new User();
	    	user.setId(supplier.getId());
	    	if(supplier.getStatus()==3){
	    		logger.debug("供应商冻结");
	        	user.setIsable(Byte.decode(CommonConstants.USER_ISABLE_NO));
	    	}else{
	    		logger.debug("供应商解冻");
	        	user.setIsable(Byte.decode(CommonConstants.USER_ISABLE_YES));

	    		//更新账号密码，并发短信
	    		//除了管理员类型的账号以外，需要随机生成密码
	        	String pass = getSmsCode();
	        	User userPass = new User();
	        	userPass.setPassword(MD5.getMD5Str(pass));
	        	userPass.setId(supplier.getId());
	        	iUserService.updatePassword(userPass);
	        	
	        	//通过短息的形式发送密码给用户
	            if (!sendMessage(supplier.getPersonTel(), SmsCodeType.SEND_USER_PWD.getCodeType(), pass))
	            	throw new BizException("给用户发送密码短信接口异常:7071");
	    	}
	    	
	    	iUserService.frozenOrEnableUser(user);
	    	
	    	//2.设置供应商表状态
			Supplier supplier1 = getSupplierById(supplier);
			supplier1.setStatus(supplier.getStatus());//设置状态为冻结：3 ；解冻（正常）：1
			supplier1.setUpdateId(supplier.getUpdateId());
			supplier1.setUpdateTime(supplier.getUpdateTime());
	    	supplierMapper.updateByPrimaryKeySelective(supplier1);
    	
    	} catch (Exception e) {
    		e.printStackTrace();
	    	if(supplier.getStatus()==3){
				logger.error("供应商冻结异常:" + e.getMessage());
	    		result = getResult(ResultEnum.CONGEALNO_SUPPLIER_EXCEPTION);
				throw new BizException("供应商冻结异常:70016");
	    	}else{
				logger.error("供应商解冻异常:" + e.getMessage());
	    		result = getResult(ResultEnum.CONGEALYES_SUPPLIER_EXCEPTION);
				throw new BizException("供应商解冻异常:70015");
	    	}
    	}
    	return result;
    }

	@Override
    @Transactional(rollbackFor=Exception.class)
	public Result examineSupplier(Supplier supplier) throws BizException {
		if(supplier.getStatus()==2){
    		logger.debug("供应商审核不通过");
    	}else{
    		logger.debug("供应商审核通过");
    	}
		
		//1.更新供应商表，修改状态
		Supplier supplier1 = getSupplierById(supplier);
		supplier1.setStatus(supplier.getStatus());//设置状态为审核通过（正常）：1 ；审核不通过：2
		supplier1.setUpdateId(supplier.getUpdateId());
		supplier1.setUpdateTime(supplier.getUpdateTime());
    	supplierMapper.updateByPrimaryKeySelective(supplier1);
    	
    	//2.如果为审核通过，更新密码并发短信
    	if(supplier.getStatus()==1){
    		
    		//除了管理员类型的账号以外，需要随机生成密码
        	String pass = getSmsCode();
        	User user = new User();
        	user.setPassword(MD5.getMD5Str(pass));
        	user.setId(supplier.getId());
        	iUserService.updatePassword(user);
        	
        	//通过短息的形式发送密码给用户
            if (!sendMessage(supplier.getPersonTel(), SmsCodeType.SEND_USER_PWD.getCodeType(), pass))
            	throw new BizException("给用户发送密码短信接口异常:7071");
            
    	}
    	
        return getResult(ResultEnum.SUCCESS);
	}
	
    @Override
	public SupplierVo getSupplierVoDetail(SupplierVo supplierVo) {
		SupplierVo supplierDetail = supplierMapper.getSupplierDetail(supplierVo);
		return supplierDetail;
	}

	@Override
	public Result getBalanceSupplierVoPageList(PageBean page,SupplierBalanceRecordVo supplierBalanceR) {
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<SupplierBalanceRecordVo> list = (Page<SupplierBalanceRecordVo>)supplierMapper.getBalanceSupplierVoListByPage(supplierBalanceR);
		PageInfo<SupplierBalanceRecordVo> pageInfo=new PageInfo<SupplierBalanceRecordVo>(list);
		return getResult(ResultEnum.SUCCESS,pageInfo.getList(),pageInfo.getTotal());

	}

	@Override
	public Supplier getSupplierById(Supplier supplier) {
		return supplierMapper.selectByPrimaryKey(supplier);
	}

    //发送短信接口
    private boolean sendMessage(String phone,String type,String message) {
    	logger.info("短信发送接口入参,phone={},type={}",phone,type);
    	Result result = smsCodeSendService.sendSmsCodeByCustomMsg(phone, type, message);
    	logger.info("短信发送接口返回值,result={}",JSON.toJSONString(result));
    	if (null != result && ResultEnum.SUCCESS.getCode().equals(result.getCode())) return true;
    	return false;
    }
    

    /**
     * 新增供应商充值记录
     * @param supplierChargeRecord 供应商充值记录
     * @return Result
     */
	@Override
	public Result addSupplierChargeRecord(SupplierChargeRecord supplierChargeRecord) throws Exception {
		this.supplierChargeRecordMapper.addSupplierChargeRecord(supplierChargeRecord);
		return  getResult(ResultEnum.SUCCESS);
	}

    /**
     * 新增供应商提现记录
     * @param memberDrawcashRecord 商户充值记录
     * @return Result
     */
	@Override
	public Result addSupplierDrawcashRecord(SupplierDrawcashRecord supplierDrawcashRecord) throws Exception {
		this.supplierDrawcashRecordMapper.addSupplierDrawcashRecord(supplierDrawcashRecord);
		return  getResult(ResultEnum.SUCCESS);
	}
}
